package net.joint_painting.server.manager;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.joint_painting.server.model.MemCache;

/**
 * @author CAM
 * @version $Revision: 1.0 $
 */
public class UpdatesManager implements Serializable {

    /**
	 * 
	 */
    private static final long serialVersionUID = -3477421911356133994L;

    /**
     * Method addSurface.
     * 
     * @param id
     *            String
     */
    public static void addSurface(String id) {
	UpdatesManager updates = (UpdatesManager) MemCache
		.getCached(UpdatesManager.class.getName() + serialVersionUID);
	if (updates == null)
	    updates = new UpdatesManager();
	updates.surfaces.add(id);
	updates.dates.put(id, new Date());
	MemCache.cache(UpdatesManager.class.getName() + serialVersionUID,
		updates);
    }

    /**
     * Method getUpdates.
     * 
     * @return List<String>
     */
    public static List<String> getUpdates() {
	UpdatesManager updates = (UpdatesManager) MemCache
		.getCached(UpdatesManager.class.getName() + serialVersionUID);
	if (updates == null)
	    updates = new UpdatesManager();

	updates.update();

	MemCache.cache(UpdatesManager.class.getName() + serialVersionUID,
		updates);
	List<String> list = new LinkedList<String>();
	list.addAll(updates.surfaces);
	return list;
    }

    private Set<String> surfaces = new HashSet<String>();

    private Map<String, Date> dates = new HashMap<String, Date>();

    private UpdatesManager() {
    }

    private void update() {
	for (String s : dates.keySet()) {
	    Date newDate = new Date();
	    Date d = dates.get(s);
	    if ((newDate.getSeconds() - d.getSeconds()) > 5) {
		dates.remove(s);
		surfaces.remove(s);
	    }
	}
    }
}
